package org.lzh.controller;

import org.lzh.pojo.TestPaper;
import org.lzh.pojo.User;
import org.lzh.service.AnswerService;
import org.lzh.service.LoginService;
import org.lzh.service.TestPaperService;
import org.lzh.util.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import java.util.List;


@Controller
public class LoginController {

    @Autowired
    private LoginService loginService;
    @Autowired
    private TestPaperService testPaperService;
    @Autowired
    private AnswerService answerService;            //用于看该学生是否考过试了

    @RequestMapping(value = "login.action", method = RequestMethod.POST)
    public String login(@RequestParam("id")String id,
                        @RequestParam("password")String password ,
                        HttpSession session,
                        TestPaper testPaper,
                        Model model){
        if(loginService.login(id,password)!=null){
            User user=loginService.login(id,password);
            session.setAttribute("user_session",user);
            if(user.getStudentOrTeacher()==1){
                return "teacher";
            }
            if(user.getStudentOrTeacher()==0){
                //先查询学生有没有做过试卷，做过的话就出字，没做过就出试卷
                if(answerService.findByStudentId(id)!=null&&answerService.findByStudentId(id).getState()==1){
                    model.addAttribute("alreadyTest","您已经做过试卷了，请耐心老师批改试卷");

                }else if(answerService.findByStudentId(id)!=null&&answerService.findByStudentId(id).getState()==0){
                    //只显示进入了的那张试卷
                     TestPaper onlyTestPaper=testPaperService.findById(answerService.findByStudentId(id).getTestPaperId());
                    model.addAttribute("onlyTestPaper",onlyTestPaper);

                }else{
                    //查询出所有的试卷
                    List<TestPaper> studentList1=testPaperService.findAllTestPaper();
                    model.addAttribute("studentList",studentList1);

                }

                return "student";
            }
        }

        model.addAttribute("tip","账号或密码错误");
        return "login" ;
    }


    //用freemarker跳到登录页面
    @RequestMapping("/")
    public String index(Model model){
        return "login";
    }



}
